<?php

namespace app\api\controller;

use app\admin\model\Notice AS NoticeMdl;
use app\common\redis\Redis;

class Notice extends BaseController
{

    /**
     * 列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [];
        $fields = "a.id,a.title,a.content,a.createDate,d.name";
        $list = NoticeMdl::alias('a')
            ->where($where)
            ->join('department d','a.departmentId = d.id')
            ->field($fields)
            ->order('createDate DESC')
            ->limit($start, $length)
            ->select();
        $total = NoticeMdl::where($where)->count();

        if (empty($list)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到公告');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list, $total);
    }


    /**
     * 详情
     */
    public function getDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->id)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'a.id' => $param->id
        ];
        $fields = "a.*,d.name";
        $item = NoticeMdl::alias('a')
            ->join('department d','a.departmentId = d.id')
            ->field($fields)
            ->where($where)
            ->find();
        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到公告');
        }
        //浏览量加1
        $realclick = $this->addreadCount($param->id,$item->readCount);
        $item['readCount'] = $realclick;
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    //浏览量加1（redis）
    private function addreadCount($id,$readCount){
        $redis = Redis::getRedisConn();
        $click = $redis->incr('notice_'.$id);
        $realclick = $click + $readCount;
        return $realclick;
    }

}